﻿using Domain.Material_Management;
using Domain.Production_Modules;
using Infratructure.Interface;
using MediatR;
using MES.Server.API.Application.Command.QualityInspection_ModCom;
using MES.Server.API.Dto.QualityInspection_DTO;
using Microsoft.EntityFrameworkCore;
using ReturnValue;

namespace MES.Server.API.Application.Handler.QualityInspection_ModHandler.NewQualityInspectionCommandHandler
{
    public class GetProductionCascaderHandlers : IRequestHandler<GetProductionCascaderCommands, ApiResult<ProductionCascaderDto>>
    {
        private readonly IRepository<ProduceModel> _produceRepo;
        private readonly IRepository<MaterialGroupModel> _materialGroupRepo;

        public GetProductionCascaderHandlers(
            IRepository<ProduceModel> produceRepo,
            IRepository<MaterialGroupModel> materialGroupRepo)
        {
            _produceRepo = produceRepo;
            _materialGroupRepo = materialGroupRepo;
        }

        public async Task<ApiResult<ProductionCascaderDto>> Handle(GetProductionCascaderCommands request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<ProductionCascaderDto>();

            var productionItems = await _produceRepo.GetAll()
                .Where(p => p.ProduceNum == p.FinishProduceNum)
                .Select(p => new ProductionItemDto
                {
                    Id = p.Id,
                    ProduceCode = p.ProduceCode,
                    ProduceName = p.ProduceName,
                    MaterialGroupId = p.MaterialGroupId,
                    ProduceNum = p.ProduceNum
                })
                .OrderByDescending(p => p.Id)
                .ToListAsync(cancellationToken);

            var materialGroupItems = await _materialGroupRepo.GetAll()
                .Select(g => new MaterialGroupItemDto
                {
                    Id = g.Id,
                    MaterialGroupCode = g.MaterialGroupCode,
                    MaterialGroupName = g.MaterialGroupName
                })
                .OrderBy(g => g.MaterialGroupName)
                .ToListAsync(cancellationToken);

            var cascaderData = new ProductionCascaderDto
            {
                ProductionItems = productionItems,
                MaterialGroupItems = materialGroupItems
            };

            return result.Success("获取联动数据成功", cascaderData);
        }
    }
}
